﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PMS.Logic.PM
{
    public partial class BottleAnalyseAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            String methodName = Request["method"];
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);
            if (method == null) throw new Exception("method is null");
            try
            {
                method.Invoke(this, null);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取气瓶分析信息
        /// </summary>
        public void GetBottleAnalyseList()
        {
            List<SearchCondition> listSearch = new List<SearchCondition>();
            if (Request.Form["searchData"] != null)
            {
                string searchData = Request.Form["searchData"];
                listSearch = ModelTools.GetSearchContions(searchData);
                if (listSearch.Where(s => s.Field == "startAnalyseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "startAnalyseDate").FirstOrDefault().Field = "AnalyseDate";
                }
                if (listSearch.Where(s => s.Field == "endAnalyseDate").FirstOrDefault() != null)
                {
                    listSearch.Where(s => s.Field == "endAnalyseDate").FirstOrDefault().Field = "AnalyseDate";
                }
            }
            Expression<Func<View_PM_BottleAnalyseList, bool>> exp = SearchExpression.FindByGroup<View_PM_BottleAnalyseList>(listSearch);
            string OrderId = OperateContext.Sort == null ? "ID" : OperateContext.Sort;
            Boolean OrderSort = OrderId == "ID" ? false : OperateContext.Order;
            int count = 0;
            var list = DALSession.Current.View_PM_BottleAnalyseListDAL.GetPagedList(OperateContext.Page, OperateContext.Rows, exp, OrderId, OrderSort);
            count = DALSession.Current.View_PM_BottleAnalyseListDAL.GetCount(exp);
            Response.Write(JsonHelper.toPageJson(list, count));
        }

        /// <summary>
        /// 通过ID或者气瓶流水号获取气瓶分析信息
        /// </summary>
        public void GetBottleAnalyseByIDCode()
        {
            //通过ID查询
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int id = Commons.String2Int32(Request.Form["ID"]);
                var per = DALSession.Current.View_PM_BottleAnalyseListDAL.GetListBy(p => p.ID == id).FirstOrDefault();
                if (!string.IsNullOrEmpty(per.AnalyseDate))
                {
                    per.AnalyseDate = per.AnalyseDate.Substring(0, 10);
                }

                Response.Write(JsonHelper.toJson(per));
                return;
            }
            //通过流水号查询
            if (Request.Form["BarCode"] != null && Request.Form["BarCode"] != "")
            {
                string Code = Request.Form["BarCode"];
                var per = DALSession.Current.View_PM_BottleAnalyseListDAL.GetListBy(p => p.SerialCode == Code).FirstOrDefault();
                if (per == null) per = new View_PM_BottleAnalyseList();
                Response.Write(JsonHelper.toJson(per));
            }
            else
            {
                Response.Write(JsonHelper.toJson(new View_PM_BottleAnalyseList()));
            }
        }

        /// <summary>
        /// 通过ID或者绑定气瓶信息
        /// </summary>
        public void GetBindBottleInfoByID()
        {
            //通过ID查询
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int id = Commons.String2Int32(Request.Form["ID"]);
                var per = DALSession.Current.View_PM_BottleAnalyseListDAL.GetListBy(p => p.ID == id).FirstOrDefault();
                if (!string.IsNullOrEmpty(per.AnalyseDate))
                {
                    per.AnalyseDate = per.AnalyseDate.Substring(0, 10);
                }
                var perBottle = DALSession.Current.View_BD_BottleInfoDAL.GetListBy(p => p.ID == per.BottleID).FirstOrDefault();

                Response.Write(JsonHelper.toJson(new
                {
                    obj = per,
                    LastCheckDate = perBottle.LastCheckDate,
                    MadeCode = perBottle.MadeCode,
                    MadeCodeID = perBottle.BottleSupplierID,
                    ProductionDate = perBottle.ProductionDate,
                    BottleSupplier = perBottle.BottleSupplier,
                    BottleNote = perBottle.Note
                }));
            }
        }

        /// <summary>
        /// 通过ID或者气瓶流水号获取气瓶分析结果
        /// </summary>
        public void GetBottleAnalyseRes()
        {
            //通过ID查询
            if (Request.Form["ID"] != null && Request.Form["ID"] != "")
            {
                int id = Commons.String2Int32(Request.Form["ID"]);
                var list = DALSession.Current.View_PM_BottleAnalyseDetailDAL.GetListBy(u => u.MainId == id).ToList();
                var perMain = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.ID == id).FirstOrDefault();
                //带出分析完成的相同产品的标准气浓度和瓶号
                if (perMain.AnalyseRes == "2")
                {
                    foreach (var detail in list)
                    {
                        var gasDetail = DALSession.Current.BD_GasInfoDAL.GetListBy(b => b.ID == detail.GasID).FirstOrDefault();
                        if (gasDetail != null)
                        {
                            detail.AnalStandardBottleCode = gasDetail.AnalStandardBottleCode;
                            detail.AnalStandardConc = gasDetail.AnalStandardConc;
                        }
                    }
                }

                Response.Write(JsonHelper.toJson(list.OrderBy(p => p.OperOrder)));
                return;
            }
            //通过流水号查询
            if (Request.Form["BarCode"] != null && Request.Form["BarCode"] != "")
            {
                string Code = Request.Form["BarCode"];
                //先通过流水号查出id
                PM_BottleProduction mainModel = DALSession.Current.PM_BottleProductionDAL.GetListBy(p => p.SerialCode == Code).FirstOrDefault();
                //流水号有误
                if (mainModel == null) return;
                var list = DALSession.Current.View_PM_BottleAnalyseDetailDAL.GetListBy(p => p.MainId == mainModel.ID).ToList();
                var perMain = DALSession.Current.PM_BottleProductionDAL.GetListBy(c => c.ID == mainModel.ID).FirstOrDefault();
                //带出分析完成的相同产品的标准气浓度和瓶号
                if (perMain.AnalyseRes == "2")
                {
                    foreach (var detail in list)
                    {
                        var gasDetail = DALSession.Current.BD_GasInfoDAL.GetListBy(b => b.ID == detail.GasID).FirstOrDefault();
                        if (gasDetail != null)
                        {
                            detail.AnalStandardBottleCode = gasDetail.AnalStandardBottleCode;
                            detail.AnalStandardConc = gasDetail.AnalStandardConc;
                        }
                    }
                }
                Response.Write(JsonHelper.toJson(list.OrderBy(p => p.OperOrder)));
            }
        }

        /// <summary>
        /// 修改分析结果
        /// </summary>
        public void EditAnalyseRes()
        {
            string detailString = Request.Form["Detail"];
            string analyseRes = Request.Form["AnalyseRes"];
            List<PM_BottleProductionDetail> detailList = JsonConvert.DeserializeObject<List<PM_BottleProductionDetail>>(detailString).ToList();

            foreach (var detail in detailList)
            {
                if (analyseRes == "2")
                {
                    //未分析，则全部保存
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "AnalyseConcentration", "AnalyseMethod", "AnalyseFile", "PrintUnit", "PrintConcentration", "AnalyseNote", "PrintDigitNum", "AnalStandardConc", "AnalStandardBottleCode");
                    //同时将标准气瓶号和浓度保存进气体信息表
                    var gasInfo = DALSession.Current.BD_GasInfoDAL.GetListBy(d => d.ID == detail.GasID).FirstOrDefault();
                    gasInfo.AnalStandardBottleCode = detail.AnalStandardBottleCode;
                    gasInfo.AnalStandardConc = detail.AnalStandardConc;
                    DALSession.Current.BD_GasInfoDAL.ModifyBy(gasInfo, d => d.ID == gasInfo.ID, "AnalStandardConc", "AnalStandardBottleCode");
                }
                else
                {
                    //否则只允许更改打印单位、浓度与打印有效数字位数
                    DALSession.Current.PM_BottleProductionDetailDAL.ModifyBy(detail, d => d.ID == detail.ID, "PrintUnit", "PrintConcentration", "PrintDigitNum");
                }
            }
            DALSession.Current.BD_GasInfoDAL.SaveChanges();
            DALSession.Current.PM_BottleProductionDetailDAL.SaveChanges();
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 检定气瓶气体是否合格
        /// </summary>
        public void CheckBottleGas()
        {
            string code = Request.Form["BarCode"];
            String res = Request.Form["res"];
            PM_BottleProduction per = DALSession.Current.PM_BottleProductionDAL.GetListBy(d => d.SerialCode == code).FirstOrDefault();
            if (per == null)
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "流水号有误"));
                return;
            }
            //更新气瓶分析师、分析日期以及分析结果
            per.AnalystID = OperateContext.SessBasicInfo.UserInfo.Id;
            per.AnalyseDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            per.ConfirmDate = DateTime.Now.ToString("yyyy-MM-dd");
            per.AnalyseRes = res == "true" ? "0" : "1";
            //气瓶状态更新为分析完成
            per.State = "2";
            DALSession.Current.PM_BottleProductionDAL.ModifyAllModel(per);
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            //更新订单完成状态
            ProductOrderAjax.SetProductOrderIsComplete((int)per.ProductOrderID);
            Response.Write(JsonHelper.toDefaultMsg(true, "保存成功"));
        }

        /// <summary>
        /// 分析反审
        /// </summary>
        public void RedoAnalyse()
        {
            int id = Convert.ToInt32(Request.Form["ID"]);
            var per = DALSession.Current.PM_BottleProductionDAL.GetListBy(d => d.ID == id).FirstOrDefault();
            if (per.State != "2")
            {
                Response.Write(JsonHelper.toDefaultMsg(false, "当前气瓶状态不是 [分析完成]，无法进行反审！"));
                return;
            }
            per.State = "1";
            per.AnalyseRes = "2";
            per.AnalyseDate = null;
            per.AnalystID = null;
            DALSession.Current.PM_BottleProductionDAL.ModifyBy(per, p => p.ID == id, "State", "AnalyseRes", "AnalyseDate", "AnalystID");
            DALSession.Current.PM_BottleProductionDAL.SaveChanges();
            //更新订单完成状态
            ProductOrderAjax.SetProductOrderIsComplete((int)per.ProductOrderID);
            Response.Write(JsonHelper.toDefaultMsg(true, "反审成功"));
        }

    }
}